package com.pushups.dao;

/**
 * Created with IntelliJ IDEA.
 * User: Vladimir
 * Date: 1/21/14
 * Time: 2:29 PM
 * To change this template use File | Settings | File Templates.
 */

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.pushups.db.DBHelper;

public class PushupsProgramDAO {
    DBHelper sqlHelper;
    String dbtable = "PushupsProgram";

    public PushupsProgramDAO(Context context){
        this.sqlHelper = new DBHelper(context);
    }

    //returns Cursor for reading records from database table
    public Cursor getCursor(String dbtable, Context context){
        SQLiteDatabase db = sqlHelper.getReadableDatabase();
        Cursor cursor = db.query(dbtable,null,null,null,null,null, null);

        return cursor;
    }

    public Week GetCurrentWeekDay(Context context, String category){
        String value= DatabaseUtils.sqlEscapeString(category);
        String sql = "select _id, week_num, day_num from PushupsProgram where completed ==0 order by _id limit 1";

        Week week = new Week();
        try{
            SQLiteDatabase db = sqlHelper.getReadableDatabase();
            Cursor cursor = db.rawQuery(sql,null);

            if(cursor!=null){
                while(cursor.moveToNext()){
                    week.setId(cursor.getInt(0));
                    week.setDay_num(cursor.getInt(1));
                }
            }
        }catch(Exception e){
            Log.e("DBQueryError: ",e.getMessage());
        }
        closeDB();
        return week;
    }

    public ArrayList<DayOfWeek> getSetsForDay(Context context, int category, int week_num, int day_num){
        String sql = "select set_num, reps_num from PushupsProgram where week_num == "+week_num+
                " and day_num == "+day_num+" and category_type == "+category;

        ArrayList<DayOfWeek> daysOfWeek = new ArrayList<DayOfWeek>();
        try{
            SQLiteDatabase db = sqlHelper.getReadableDatabase();
            Cursor cursor = db.rawQuery(sql,null);
            if(cursor!=null){
                while(cursor.moveToNext()){
                    DayOfWeek t = new DayOfWeek();
                    t.setSet_num(cursor.getInt(0));
                    t.setReps_num(cursor.getInt(1));
                    daysOfWeek.add(t);
                }
            }
            //closeDB();
        }catch(Exception e){
            Log.e("DBQueryError: ",e.getMessage());
        }
        closeDB();
        return daysOfWeek;
    }


    public void closeDB(){
        sqlHelper.close();
    }
}

